﻿using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using Cubicle.Nuget.Config;

namespace Cubicle.Nuget.Core
{

    [Export]
    public class ClientManager : IEnumerable<NugetClient>
    {
        [Export] 
        public List<NugetClient> Clients = new List<NugetClient>();

        [Export("default")] 
        public NugetClient DefaultClient
        {
            get { return Clients.FirstOrDefault(x => x.IsDefault); }
        }

        public ClientManager()
        {
            foreach (var feed in NugetConfig.Singleton.Feeds)
                AddFeed(feed.Name, feed.IsDefault, feed.Uri);
        }

        public bool AddFeed(string name, bool isDefault, string uri)
        {
            Clients.Add(new NugetClient(name, isDefault, uri));
            return true;
        }

        public bool RemoveFeed(string name)
        {
            var client = Clients.FirstOrDefault(x => x.Name == name);
            return Clients.Remove(client);
        }

        public bool SetDefault(string name)
        {
            var newDefault = Clients.FirstOrDefault(x => x.Name == name);
            if (newDefault == null) return false;
            DefaultClient.IsDefault = false;
            newDefault.IsDefault = true;
            return true;
        }

        public NugetClient this[string name]
        {
            get
            {
                return string.IsNullOrEmpty(name) 
                    ? DefaultClient 
                    : Clients.FirstOrDefault(x => x.Name == name);
            }
        }

        public IEnumerator<NugetClient> GetEnumerator()
        {
            return Clients.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
}